package com.xuecheng.media.api;

import com.onlinelearn.base.exception.OnlineLearnException;
import com.onlinelearn.base.model.PageParams;
import com.onlinelearn.base.model.PageResult;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Mr.M
 * @version 1.0
 * @description 媒资文件管理接口
 * @date 2022/9/6 11:29
 */
@Api(value = "媒资文件管理接口", tags = "媒资文件管理接口")
@RestController
public class MediaFilesController {


    @Autowired
    MediaFileService mediaFileService;


    @ApiOperation("媒资列表查询接口")
    @PostMapping("/files")
    public PageResult<MediaFiles> list(PageParams pageParams, @RequestBody QueryMediaParamsDto queryMediaParamsDto) {
        Long companyId = 1232141425L;
        return mediaFileService.queryMediaFiels(companyId, pageParams, queryMediaParamsDto);

    }

    @ApiOperation("图片上传")
    @RequestMapping(value = "/upload/coursefile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public UploadFileResultDto upload(@RequestPart("filedata") MultipartFile upload,@RequestParam(value = "objectName",required = false) String objectName) throws IOException {
        Long companyId = 1232141425L;

        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        uploadFileParamsDto.setFilename(upload.getOriginalFilename());
        uploadFileParamsDto.setFileSize(upload.getSize());
//        数据字典:文件类型
        uploadFileParamsDto.setFileType("001001");

        //        在服务器端创建临时文件
        File temp = File.createTempFile("minio",".temp");
        upload.transferTo(temp);

        UploadFileResultDto uploadFileResultDto = mediaFileService.uploadFile(companyId, uploadFileParamsDto, temp.getAbsolutePath(),objectName);

        if(uploadFileResultDto == null){
            OnlineLearnException.cast("上传文件失败!");
        }

//        这是新加的,接口结束,删除临时文件
        temp.delete();
        return uploadFileResultDto;
    }

}
